package com.example.demo.controller;

import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    //登录
    @PostMapping("/login")

    public String login(String username, String password, HttpServletResponse response, Model model) {
        Map<String, String> map = userService.login(username, password);
        if (map.containsKey("error")) {
            model.addAttribute("error", map.get("error"));
            return "/error";

        } else {
            Cookie cookie = new Cookie("ticket", map.get("ticket"));
            cookie.setMaxAge(1000000);
            response.addCookie(cookie);
            return "/index";
        }
    }

    //登录页面
    @GetMapping("/loginPage")
    public String getLoginPage() {
        return "/login";
    }

    //登出
    @ResponseBody
    @PostMapping("/logout")
    public String loginOut(@CookieValue("ticket") String ticket) {
        return userService.logout(ticket);
    }

    //错误页面
    @GetMapping("/error")
    public String error() {
        return "/error";
    }

    //INDEX页面
    @GetMapping("/index")
    public String getIndexPage() {
        return "/index";
    }

}
